<template>
  <div>
    <Card _Title="资金管理" :_Size="16"></Card>
    <div>
      <div>
        <span class="text-color fontsize-16">账户余额：</span>
        <span class="price-color mr_20" style="font-size:26px">{{ unitPrice(memberDeposit, '￥') }}</span>
        <span class="text-color fontsize-16 ml_10">冻结金额：</span>
        <span class="text-color fontsize-16">{{ unitPrice(frozenDeposit, '￥') }}</span>
      </div>
      <div class="mt_20 mb_20">
        <a-button @click="handleRecharge" size="small" status="danger" type="primary">在线充值</a-button>
        <a-button @click="handleWithdrawalApply" size="small" status="danger" type="outline" class="ml_10">申请提现</a-button>
      </div>
    </div>

    <a-tabs v-model:active-key="tabCurrent" @change="tabsChange">
      <a-tab-pane key="log" title="余额日志">
        <a-table :columns="logColumns" :data="logData.records" :pagination="false">
          <template #money="{ record }">
            <span v-if="record.money > 0" style="color: #00B42A;">+{{unitPrice(record.money, '￥')}}</span>
            <span v-else style="color: #F31947;">-{{unitPrice(0 - record.money, '￥')}}</span>
          </template>
          <template #detail="{ record }">
            <a-tooltip :content="record.detail" position="bottom">
              <div class="ellipsis ellipsis-1 hover-pointer">{{ record.detail }}</div>
            </a-tooltip>
          </template>
        </a-table>
        <div class="paginationBox">
          <a-pagination :total="logData.total" :current="logParams.pageNumber" :page-size="logParams.pageSize" show-page-size
                        @change="changePage($event, 'log')" @page-size-change="changePageSize($event, 'log')"></a-pagination>
        </div>
      </a-tab-pane>
      <a-tab-pane key="recharge" title="充值记录">
        <a-table :columns="rechargeColumns" :data="rechargeData.records" :pagination="false">
          <template #rechargeMoney="{ record }">
            <span v-if="record.payStatus === 'PAID'" style="color: #00B42A;">+{{unitPrice(record.rechargeMoney, '￥')}}</span>
            <span v-else>{{unitPrice(record.rechargeMoney, '￥')}}</span>
          </template>
          <template #payStatus="{ record }">
            <span v-if="record.payStatus === 'PAID'">已付款</span>
            <span v-else-if="record.payStatus === 'UNPAID'">未付款</span>
            <span v-else-if="record.payStatus === 'CANCEL'">已取消</span>
          </template>
          <template #rechargeWay="{ record }">
            <span v-if="record.rechargeWay === 'ALIPAY'">支付宝</span>
            <span v-else-if="record.rechargeWay === 'WECHAT'">微信</span>
            <span v-else-if="record.rechargeWay === 'BANK_TRANSFER'">线下转账</span>
          </template>
        </a-table>
        <div class="paginationBox">
          <a-pagination :total="rechargeData.total" :current="rechargeParams.pageNumber" :page-size="rechargeParams.pageSize" show-page-size
                        @change="changePage($event, 'recharge')" @page-size-change="changePageSize($event, 'recharge')"></a-pagination>
        </div>
      </a-tab-pane>
      <a-tab-pane key="withdrawApply" title="提现记录">
        <a-table :columns="withdrawApplyColumns" :data="withdrawApplyData.records" :pagination="false">
          <template #applyMoney="{ record }">
            <span v-if="record.applyStatus === 'VIA_AUDITING'" style="color: #00B42A;">+{{unitPrice(record.applyMoney, '￥')}}</span>
            <span v-else>{{unitPrice(record.applyMoney, '￥')}}</span>
          </template>
          <template #applyStatus="{ record }">
            <span v-if="record.applyStatus === 'APPLY'">申请中</span>
            <span v-else-if="record.applyStatus === 'VIA_AUDITING'">审核通过</span>
            <span v-else-if="record.applyStatus === 'SUCCESS'">提现成功</span>
            <span v-else-if="record.applyStatus === 'ERROR'">提现失败</span>
            <span v-else>提现拒绝</span>
          </template>
          <template #inspectRemark="{ record }">
            <a-tooltip :content="record.inspectRemark" position="bottom">
              <div class="ellipsis ellipsis-1 hover-pointer">{{ record.inspectRemark }}</div>
            </a-tooltip>
          </template>
        </a-table>
        <div class="paginationBox">
          <a-pagination :total="withdrawApplyData.total" :current="withdrawApplyParams.pageNumber" :page-size="withdrawApplyParams.pageSize" show-page-size
                        @change="changePage($event, 'withdrawApply')" @page-size-change="changePageSize($event, 'withdrawApply')"></a-pagination>
        </div>
      </a-tab-pane>
    </a-tabs>

    <!--在线充值modal-->
    <a-modal v-model:visible="rechargeModal">
      <template #title>充值金额</template>
      <div class="">
        <a-form ref="rechargeFormRef" size="large" layout="horizontal" :style="{ width: '400px'}" auto-label-width :model="rechargeForm">
          <a-form-item field="price" label="充值金额" :rules="[REQUIRED]">
            <a-input-number v-model="rechargeForm.price" :style="{width:'320px'}" :min="0" allow-clear>
              <template #append>元</template>
            </a-input-number>
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <a-button @click="rechargeSubmit" status="success" type="primary">充值</a-button>
      </template>
    </a-modal>

    <!--提现申请modal-->
    <a-modal v-model:visible="withdrawApplyModal">
      <template #title>提现申请</template>
      <div class="">
        <div v-if="withdrawApplyForm.bindWechat">
          <a-form ref="withdrawApplyFormRef" size="large" layout="horizontal" :style="{ width: '400px'}" auto-label-width :model="withdrawApplyForm">
            <a-form-item field="price" label="提现金额" :rules="[REQUIRED, MONEY]" class="tixian">
              <a-input-number v-model="withdrawApplyForm.price" :min="0" allow-clear style="">
                <template #append>元</template>
              </a-input-number>
              <span style="color: red" v-if="withdrawApplyForm.minPrice && withdrawApplyForm.maxPrice">
                一次性可以提现  {{ withdrawApplyForm.minPrice }}~{{ withdrawApplyForm.maxPrice }}元</span>
            </a-form-item>
            <a-form-item field="realName" label="真实姓名" :rules="[REQUIRED]" v-if="withdrawApplyForm.type === 'ALI'">
              <a-input v-model="withdrawApplyForm.realName" allow-clear :style="{ width: '320px' }" />
            </a-form-item>
            <a-form-item field="connectNumber" label="第三方登录账号" :rules="[REQUIRED]" v-if="withdrawApplyForm.type === 'ALI'">
              <a-input v-model="withdrawApplyForm.connectNumber" allow-clear :style="{ width: '320px' }" />
            </a-form-item>
          </a-form>
        </div>
        <div v-else style="text-align:center">
          <span>提现需绑定微信：</span>
          <a-button @click="handleBindWechat" status="success" type="primary">绑定微信</a-button>
        </div>
      </div>
      <template #footer>
        <a-button @click="withdrawalSubmit" status="success" type="outline" :disabled="!withdrawApplyForm.bindWechat">提现</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { useRouter } from 'vue-router';
  import { ref, onMounted } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import storage from '@/utils/storage';
  import { unitPrice } from '@/utils/filters';
  import {getDepositLog, getMembersWallet, getRecharge, getWithdrawApply, recharge, withdrawalApply} from '@/api/member';
  import { withdrawalSettingVO } from "@/api/pay";
  import { REQUIRED, MONEY } from '@/utils/validator';
  import { gatewayUrl } from '@/utils/axios';

  const router = useRouter();
  const frozenDeposit = ref(0); // 冻结余额
  const memberDeposit = ref(0); // 余额
  // 当前tab栏
  const tabCurrent = ref('log');
  // 余额日志请求参数
  const logParams = ref({
    pageNumber: 1,
    pageSize: 10
  });
  const logData = ref<any>();
  const logColumns: any = [
    {title: '时间', width: 200, dataIndex: 'createTime', align: 'center' },
    {title: '金额', width: 140, dataIndex: 'money', slotName: 'money', align: 'center' },
    {title: '变动日志', dataIndex: 'detail', slotName: 'detail' }
  ];
  // 充值记录
  const rechargeParams = ref({
    pageNumber: 1,
    pageSize: 10
  });
  const rechargeData = ref<any>('');
  const rechargeColumns: any = [
    {title: '充值时间', width: 190, dataIndex: 'createTime', align: 'center' },
    {title: '支付单号', width: 200, dataIndex: 'rechargeSn', align: 'center' },
    {title: '充值金额', width: 120, dataIndex: 'rechargeMoney', slotName: 'rechargeMoney', align: 'center' },
    {title: '支付状态', dataIndex: 'payStatus', slotName: 'payStatus', align: 'center' },
    {title: '支付方式', dataIndex: 'rechargeWay', slotName: 'rechargeWay', align: 'center' },
    {title: '支付时间', width: 190, dataIndex: 'payTime', align: 'center' },
  ];
  // 提现记录
  const withdrawApplyParams = ref({
    pageNumber: 1,
    pageSize: 10
  });
  const withdrawApplyData = ref<any>('');
  const withdrawApplyColumns: any = [
    {title: '申请时间', width: 190, dataIndex: 'createTime', align: 'center' },
    {title: '提现单号', width: 210, dataIndex: 'sn', align: 'center' },
    {title: '提现金额', width: 120, dataIndex: 'applyMoney', slotName: 'applyMoney', align: 'center' },
    {title: '提现状态', dataIndex: 'applyStatus', slotName: 'applyStatus', align: 'center' },
    {title: '审核时间', width: 190, dataIndex: 'inspectTime', align: 'center' },
    {title: '审核备注', dataIndex: 'inspectRemark', slotName: 'inspectRemark', align: 'center' },
  ];
  // 在线充值modal
  const rechargeModal = ref(false);
  const rechargeFormRef = ref();
  const rechargeForm = ref<any>({});
  // 申请提现modal
  const withdrawApplyModal = ref(false);
  const withdrawApplyFormRef = ref();
  const withdrawApplyForm = ref({
    price: 1,
    minPrice: 1,
    maxPrice: 200,
    type: 'WECHAT',
    bindWechat: false,
    realName: '',
    connectNumber: '',
  });


  // tab切换
  const tabsChange = (value: any) => {
    tabCurrent.value = value;
    // 如果是余额日志
    if (value === 'log') {
      logParams.value.pageSize = 10;
      logParams.value.pageNumber = 1;
      getLogData();
    }
    // 如果查询充值记录
    if (value === 'recharge') {
      rechargeParams.value.pageSize = 10;
      rechargeParams.value.pageNumber = 1;
      getRechargeData();
    }
    // 如果是提现记录
    if (value === 'withdrawApply') {
      withdrawApplyParams.value.pageSize = 10;
      withdrawApplyParams.value.pageNumber = 1;
      getWithdrawApplyData();
    }
  };
  // 分页页数改变时触发
  const changePage = (event: any, type: any) => {
    if (type === 'log') {
      logParams.value.pageNumber = event;
      getLogData();
    } else if (type === 'recharge') {
      rechargeParams.value.pageNumber = event;
      getRechargeData();
    } else if (type === 'withdrawApply') {
      withdrawApplyParams.value.pageNumber = event;
      getWithdrawApplyData();
    }
  };
  // 分页条数改变时触发
  const changePageSize = (event: any, type: any) => {
    if (type === 'log') {
      logParams.value.pageSize = event;
      logParams.value.pageNumber = 1;
      getLogData();
    } else if (type === 'recharge') {
      rechargeParams.value.pageSize = event;
      rechargeParams.value.pageNumber = 1;
      getRechargeData();
    } else if (type === 'withdrawApply') {
      withdrawApplyParams.value.pageSize = event;
      withdrawApplyParams.value.pageNumber = 1;
      getWithdrawApplyData();
    }
  };

  // 初始化数据
  const init = () => {
    // 查询账户余额
    getMembersWallet().then((res) => {
      if (res.data.success) {
        frozenDeposit.value = res.data.result.memberFrozenWallet;
        memberDeposit.value = res.data.result.memberWallet;
      }
    });
  };
  // 查询余额日志
  const getLogData = () => {
    // 查询余额列表
    getDepositLog(logParams.value).then((res) => {
      if (res.data.success) {
        logData.value = res.data.result;
      }
    });
  };
  // 查询充值记录
  const getRechargeData = () => {
    getRecharge(rechargeParams.value).then((res) => {
      if (res.data.success) {
        rechargeData.value = res.data.result;
      }
    });
  };
  // 查询提现记录
  const getWithdrawApplyData = () => {
    getWithdrawApply(withdrawApplyParams.value).then((res) => {
      if (res.data.success) {
        withdrawApplyData.value = res.data.result;
      }
    });
  };

  // 在线充值
  const handleRecharge = () => {
    rechargeModal.value = true;
  };
  const rechargeSubmit = async () => {
    const auth = await rechargeFormRef.value?.validate();
    if (!auth) {
      recharge(rechargeForm.value).then((res) => {
        if (res.data.message === 'success') {
          router.push({path: '/payment/payment', query: {orderType: 'RECHARGE', sn: res.data.result.rechargeSn}});
        }
      });
    }
  };
  // 申请提现
  const handleWithdrawalApply = () => {
    withdrawalSettingVO().then((res) => {
      withdrawApplyModal.value = true;
      if (res.data.code === 200) {
        withdrawApplyForm.value.minPrice = res.data.result.minPrice;
        withdrawApplyForm.value.maxPrice = res.data.result.maxPrice;
        withdrawApplyForm.value.bindWechat = res.data.result.bindWechat;
        withdrawApplyForm.value.type = res.data.result.type;
        withdrawApplyForm.value.price = 1;
      }
    });
  };
  const withdrawalSubmit = async () => {
    const auth = await withdrawApplyFormRef.value?.validate();
    if (!auth) {
      withdrawalApply(withdrawApplyForm.value).then((res) => {
        if (res.data && res.data.success) {
          Message.success('提现申请成功，关注提现状态');
          withdrawApplyModal.value = false;
          init(); // 余额查询
          getWithdrawApplyData(); // 提现记录
          getLogData();
        }
      });
    }
  };
  // 绑定微信
  const handleBindWechat = () => {
    // 获取访问Token
    const accessToken = storage.getAccessToken();
    window.open(`${gatewayUrl}/passport/connect/connect/bind/web/WECHAT_PC?token=${accessToken}`, 'blank');
  };
  
  onMounted(() => {
    init();
    getLogData();
  });
</script>

<style scoped lang="less">
  :deep(.arco-tabs-tab-active) {
    color: @theme_color;
  }
  :deep(.arco-tabs-nav-ink) {
    background-color: @theme_color;
  }
  :deep(.tixian .arco-form-item-content) {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

</style>
